# coding=utf-8
import json

__author__ = 'linzh'

from flask import Flask, request

from flask_restful import Resource, Api

app = Flask(__name__)

api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {"hello": "world"}

    def post(self):
        """
        写入文件
        """
        req_data = request.data
        print req_data

        # 进行解码
        data_dec = json.loads(req_data)

        fp = open('data.json', 'w')
        fp.write(req_data)
        fp.close()

        return {"post": "data"}

    def put(self):
        """
        1. 先加载源文件
        """
        req_data = request.data
        req_data_dec = json.loads(req_data)

        fp = open('data.json', 'r')

        data = fp.read()
        data_dec = json.loads(data)
        print data_dec

        return {"data": req_data_dec, "data_old": data_dec}

    def delete(self):
        fp = open('data.json', 'w')
        fp.truncate()
        fp.close()
        return {"delete": "del"}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)